//先获取数据  渲染到页面
const tbody = document.querySelector('tbody');
const addForm = document.querySelector('.add-form');
const updateForm = document.querySelector('.update-form');


function studentList() {
    axios.get('/student/list')
        .then(r => {
            console.log(r);
            if (r.data.code === 0) {
                const arr = r.data.data
                let html = arr.reduce((h, v) => h + `
            <tr>
        <th scope="row">${v.id}</th>
        <td>${v.name}</td>
        <td>${v.age}</td>
        <td>${v.sex}</td>
        <td>${v.group}</td>
        <td>${v.phone}</td>
        <td>${v.salary}</td>
        <td>${v.truesalary}</td>
        <td>${v.province + v.city + v.county}</td>
        <td>
          <button type="button" data-id = ${v.id} class="btn btn-primary btn-sm update-show-modal">修改</button>
          <button type="button" class="btn btn-danger btn-sm delete-show" data-id="${v.id}" >删除</button>
        </td>
      </tr>
            `,'')

                tbody.innerHTML = html
            }
        })
}
// url请求地址   params 请求参数   dpm 目标下拉框  label--label--下拉框的默认  value=''
function renderSelect(url, params, dom, label, value = '') {
    axios.get(url, params)
        .then(r => {
            console.log(r);
            dom.innerHTML = r.data.reduce((h, v) => h + `
       <option  value="${v}">${v}</option>
       `, ` <option selected value="">--${label}--</option>`)
            dom.value = value
        })
}


function getSelect(select) {
    const provinceSelect = document.querySelector(`${select} [name = province]`);  //省的下拉框
    const citySelect = document.querySelector(`${select} [name = city]`);          //市的下拉框
    const countySelect = document.querySelector(`${select} [name = county]`);      //县的下拉框

    renderSelect('/geo/province', {}, provinceSelect, '省')

    provinceSelect.addEventListener("change", function () {
        renderSelect('/geo/city', { params: { pname: provinceSelect.value } }, citySelect, '市')
    })

    citySelect.addEventListener("change", function () {
        renderSelect('/geo/county', { params: { pname: provinceSelect.value, cname: citySelect.value } }, countySelect, '县')
    })
}
//查询数据  页面渲染
studentList()
// 新增省市县 初始化
getSelect('#addModal')
// 编辑省市县 初始化
getSelect('#updateModal')

//添加的提交事件
addForm.addEventListener('submit', function (e) {
    //阻止默认行为
    e.preventDefault()
    //快速获取表单值
    const data = $(addForm).serialize()
    //发送请求
    axios.post('/student/add', data)
        .then(r => {
            if (r.data.code === 0) {
                // 成功表单重置
                addForm.reset()
                // 页面重新渲染最新数据
                studentList()
                // 弹出提示框
                toastr.info(r.data.message)
                // 关闭添加的拟态框
                $('#addModal').modal('hide')
            }
        })
})
// 给编辑按钮绑定点击事件 弹出编辑的拟态框
tbody.addEventListener('click', function (e) {
    const dom = e.target
    // 判断修改按钮
    if (dom.classList.contains('update-show-modal')) {
        //打开编辑拟态框
        $('#updateModal').modal('show')
        const id = dom.dataset.id

        axios.get('/student/one', { params: { id } })
            .then(r => {
                console.log(r);
                const obj = r.data.data
                for (const key in obj) {
                    const target = document.querySelector(`#updateModal [name=${key}]`)

                    if (key === 'sex') {
                        // 根据 当前 性别的值 (obj.sex ) 找到 对应的 性别 单选框  让它选中
                        // 既要找到 name = sex 而且 value = obj.sex 标签
                        document.querySelector(`#updateModal [name=sex][value = ${obj.sex}]`).checked = true;
                        continue
                    }

                    // 判断一下当前obj.key 是男 还是 女
                    // if (obj.sex === "男") {
                    //     document.querySelector(`#updateModal [name=sex][value=男]`).checked = true;
                    // } else if (obj.sex === "女") {
                    //     document.querySelector(`#updateModal [name=sex][value=女]`).checked = true;
                    // }

                    if (target) {
                        target.value = obj[key];
                    }

                }

                //显示编辑表单里 市的下拉框
                renderSelect('/geo/city', {
                    params: {
                        pname: obj.province
                    }
                }, document.querySelector('#updateModal [name=city]'), '市', obj.city)

                //显示编辑表单里 县的下拉框
                renderSelect('/geo/county', {
                    params: {
                        pname: obj.province,
                        cname:obj.city
                    }
                }, document.querySelector('#updateModal [name=county]'), '县', obj.county)
            })
    }
    //判断删除
    else if(dom.classList.contains('delete-show')){
        if(confirm('您确定要删除吗')){
            const id = dom.dataset.id
         
            axios.delete('/student/delete',{params:{id}})
            .then(r=>{
                if(r.data.code === 0){
    
                    toastr.info(r.data.message)
                    studentList()
    
                }
            })
        }
       
    }
})

//编辑完成功能
updateForm.addEventListener('submit',function(e){
     //阻止默认行为
     e.preventDefault()
     //快速获取表单值
     const data = $(updateForm).serialize()
     //发送请求
     axios.put('/student/update', data)
         .then(r => {
             if (r.data.code === 0) {
                 // 成功表单重置
                 updateForm.reset()
                 // 页面重新渲染最新数据
                 studentList()
                 // 弹出提示框
                 toastr.info(r.data.message)
                 // 关闭添加的拟态框
                 $('#updateModal').modal('hide')
             }
         })
})